package com.ruoyi.project.mobile.jiaqin;

import com.ruoyi.common.utils.*;
import com.ruoyi.common.utils.uniquekey.IdGererateFactory;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.project.AppBeanInjector;
import com.ruoyi.project.system.address.domain.MemberAddress;
import com.ruoyi.project.system.address.service.IMemberAddressService;
import com.ruoyi.project.system.goods.cart.service.IShoppingCartService;
import com.ruoyi.project.system.goods.fee.domain.GoodsPostFee;
import com.ruoyi.project.system.goods.fee.service.IGoodsPostFeeService;
import com.ruoyi.project.system.goods.img.enums.GoodsImgType;
import com.ruoyi.project.system.goods.img.service.IGoodsImgService;
import com.ruoyi.project.system.goods.product.domain.GoodsProduct;
import com.ruoyi.project.system.goods.product.service.IGoodsProductService;
import com.ruoyi.project.system.goodsteam.domain.GoodsTeam;
import com.ruoyi.project.system.goodsteam.domain.GoodsTeamDto;
import com.ruoyi.project.system.goodsteam.service.IGoodsTeamService;
import com.ruoyi.project.system.member.domain.Member;
import com.ruoyi.project.system.member.service.IMemberService;
import com.ruoyi.project.system.oederteamgoods.domain.OrderTeamGoods;
import com.ruoyi.project.system.oederteamgoods.domain.OrderTeamGoodsDto;
import com.ruoyi.project.system.oederteamgoods.service.IOrderTeamGoodsService;
import com.ruoyi.project.system.order.comment.dto.OrderCommentDto;
import com.ruoyi.project.system.order.comment.service.IOrderCommentService;
import com.ruoyi.project.system.order.commentimg.domain.CommentImg;
import com.ruoyi.project.system.order.commentimg.service.ICommentImgService;
import com.ruoyi.project.system.order.order.enums.OrderPayType;
import com.ruoyi.project.system.order.order.enums.OrderStatus;
import com.ruoyi.project.system.order.refuse.domain.OrderRefuse;
import com.ruoyi.project.system.order.refuse.service.IOrderRefuseService;
import com.ruoyi.project.system.orderteamorder.domain.OrderTeamOrder;
import com.ruoyi.project.system.orderteamorder.domain.OrderTeamOrderDto;
import com.ruoyi.project.system.orderteamorder.service.IOrderTeamOrderService;
import com.ruoyi.project.system.orderteamuser.domain.OrderTeamUser;
import com.ruoyi.project.system.orderteamuser.service.IOrderTeamUserService;
import com.ruoyi.project.system.paylog.domain.PayLog;
import com.ruoyi.project.system.paylog.service.IPayLogService;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;

/**
 * 拼团
 *
 * @autor LCL
 * @date - 2021/3/3
 */
@RestController
@RequestMapping("/api/goodsTeam")
public class ApiGoodsTeamController extends BaseController {

    @Autowired
    private IGoodsTeamService goodsTeamService;
    @Autowired
    private IGoodsImgService goodsImgService;
    @Autowired
    private IGoodsProductService goodsProductService;
    @Autowired
    private IMemberAddressService memberAddressService;
    @Autowired
    private IMemberService memberService;
    @Autowired
    private IGoodsPostFeeService goodsPostFeeService;
    @Autowired
    private IdGererateFactory idGererateFactory;
    @Autowired
    private IOrderTeamOrderService orderTeamOrderService;
    @Autowired
    private IOrderTeamGoodsService orderTeamGoodsService;
    @Autowired
    private IShoppingCartService shoppingCartService;
    @Autowired
    private IOrderCommentService orderCommentService;
    @Autowired
    private ICommentImgService commentImgService;
    @Autowired
    private IOrderRefuseService orderRefuseService;
    @Autowired
    private IPayLogService payLogService;
    @Autowired
    private IOrderTeamUserService orderTeamUserService;


    /**
     * 查询拼团商品列表
     * @param uid 用户id
     * @return
     */
    @GetMapping("/goodsTeamList")
    public R goodsTeamList(@RequestParam String uid) {
        startPage();
        GoodsTeam goodsTeam = new GoodsTeam();
        goodsTeam.setStatus(0);
        return RFactory.generateR(getDataTable(this.goodsTeamService.selectGoodsTeamList(goodsTeam)));
    }

    /**
     * 查询拼团商品详情
     * @param id 拼团商品id
     * @return
     */
    @GetMapping("/goodsTeamInfo")
    public R goodsTeamInfo(@RequestParam String uid, @RequestParam String id){
        GoodsTeam goodsTeamById = goodsTeamService.selectGoodsTeamById(id);
        HashMap<String, Object> map = new HashMap<>();
        //商品信息
        map.put("goods",goodsTeamById);
        //轮播信息
        map.put("bannerImg",this.goodsImgService.findListByGoodsIdAndType(id, GoodsImgType.BANNER.getValue()));
        //详情信息
        map.put("detailsImg",this.goodsImgService.findListByGoodsIdAndType(id,GoodsImgType.DETAILS.getValue()));
        return RFactory.generateR(map);
    }

    /**
     * 查询拼团商品规格
     * @param uid 用户id
     * @param id 拼团商品id
     * @param spec 规格
     * @return
     */
    @GetMapping("/goodsTeamSpec")
    public R goodsTeamSpec(@RequestParam String uid,@RequestParam String id,
                            @RequestParam String spec){
        return RFactory.generateR(this.goodsProductService.findBySpec(id,spec));
    }

    /**
     * 准备下单
     * @param uid 用户id
     * @param productIds 规格
     * @param nums 数量
     * @return
     */
    @GetMapping("/ready")
    public R readyOrder(@RequestParam String uid,@RequestParam String[] productIds,@RequestParam Integer[] nums){
        if(productIds.length==0){
            return R.error("请至少选一件商品");
        }
        HashMap<String, Object> map = new HashMap<>();
        //查询默认地址信息
        MemberAddress memberAddress = this.memberAddressService.findDefault(uid);
        map.put("address",memberAddress);
        //默认审核通过
        map.put("examine",0);
        //查询商品信息
        BigDecimal sumGoodsPrice = new BigDecimal(0);
        BigDecimal sumPostFee = new BigDecimal(0);
        int goodsCount = 0;
        ArrayList<GoodsTeamDto> goodsDtos = new ArrayList<>();
        Member member = this.memberService.selectMemberById(uid);
        for(int i=0;i<productIds.length;i++){
            GoodsTeamDto goodsTeamDto = this.goodsTeamService.findGoodsTeamDtoByPId(productIds[i]);
            goodsTeamDto.setTotal(nums[i]);
            goodsTeamDto.setSpecId(productIds[i]);
            goodsDtos.add(goodsTeamDto);

            sumGoodsPrice=sumGoodsPrice.add(goodsTeamDto.getPriceVip().multiply(new BigDecimal(nums[i])));

            // 获取该地区的运费
            List<GoodsPostFee> goodsPostFeeList = this.goodsPostFeeService.findListByGoodsId(goodsTeamDto.getId());
            for(GoodsPostFee goodsPostFee :goodsPostFeeList){
                if(memberAddress.getArea().indexOf(goodsPostFee.getName())!=-1){
                    goodsTeamDto.setPostFee(goodsPostFee.getPostFee());
                    break;
                }
            }
            sumPostFee=sumPostFee.add(goodsTeamDto.getPostFee());
            goodsCount=goodsCount+nums[i];
            //判断商品是否是境外商品
//            if(!goodsDto.getTag().equals(GoodsTag.QUALITY_GOODS.getValue())){
                //判断当前用户是否已认证
                if(!member.getIsExamine().equals(2)){
                    map.put("examine",1);
                }
//            }
        }
        map.put("sumPostFee",sumPostFee);
        map.put("sumGoodsPrice",sumGoodsPrice);
        map.put("sumPrice",sumGoodsPrice.add(sumPostFee));
        map.put("goods",goodsDtos);
        map.put("goodsCount",goodsCount);
        return RFactory.generateR(map);
    }

    /**
     * 新增订单
     * @param orderTeamOrderDto
     * @return
     */
    @PostMapping
    @Transactional
    public R addOrder(@RequestBody OrderTeamOrderDto orderTeamOrderDto){
        Member member = this.memberService.selectMemberById(orderTeamOrderDto.getUserId());
        // 分享人信息
//        Member shareUser = this.memberService.selectMemberById(teamId);

        // 分享人拼团订单
//        String oId = "";
//        OrderTeamOrder oto = new OrderTeamOrder();
//        oto.setStatus(9);
//        oto.setUserId(memberId);
//        // 拼团订单列表
//        List<OrderTeamOrder> teamOrderList = this.orderTeamOrderService.selectOrderTeamOrderList(oto);
//        for (OrderTeamOrder orderTeamO:teamOrderList) {
//            // 某一条拼团订单
//            OrderTeamOrderDto byOrderNo = this.orderTeamOrderService.findByOrderNo(orderTeamO.getOrderNo());
//            for(OrderTeamGoods orderTeamGoods:orderTeamOrderDto.getGoodsList()){
//                OrderTeamGoodsDto teamGoodsDto = orderTeamGoodsService.findByOrderId(byOrderNo.getId());
//                if (teamGoodsDto.getOrderId()==orderTeamGoods.getOrderId()) {
//                    oId = teamGoodsDto.getOrderId();
//                }
//            }
//
//        }

        //判断商品库存是否充足
        for(OrderTeamGoods orderTeamGoods:orderTeamOrderDto.getGoodsList()){
            GoodsProduct goodsProduct = this.goodsProductService.selectGoodsProductById(orderTeamGoods.getProductId());
            if(goodsProduct.getStock()<orderTeamGoods.getTotal()){
                return R.error("库存不足,请重新下单");
            }

            // 判断商品是否在拼单时间
            GoodsTeam goodsTeamById = this.goodsTeamService.selectGoodsTeamById(orderTeamGoods.getGoodsId());
            if (goodsTeamById.getGroupStart().getTime() > DateUtils.getNowDate().getTime() || goodsTeamById.getGroupEnd().getTime() < DateUtils.getNowDate().getTime()) {
                return R.error("不在拼团时间");
            }

            // 判断用户是否在拼团中
            OrderTeamGoods orderTeamG = new OrderTeamGoods();
            orderTeamG.setGoodsId(orderTeamGoods.getGoodsId());
            List<OrderTeamGoods> teamGoodsList = this.orderTeamGoodsService.selectOrderTeamGoodsList(orderTeamG);
            for (OrderTeamGoods oTG:teamGoodsList) {
                OrderTeamOrder byId = this.orderTeamOrderService.selectOrderTeamOrderById(oTG.getOrderId());
                if (byId.getUserId().equals(member.getId())) {
                    if (byId.getStatus() == 9 || byId.getStatus() == 0 || byId.getStatus() == 1 || byId.getStatus() == 2) {
                        return R.error("该商品正在拼团中");
                    }
                }

            }

            //修改库存
            goodsProduct.setStock(goodsProduct.getStock()-orderTeamGoods.getTotal().intValue());
            this.goodsProductService.updateGoodsProduct(goodsProduct);

            //修改商品库存
            GoodsTeam oldGoods = this.goodsTeamService.selectGoodsTeamById(goodsProduct.getGoodsId());
            GoodsTeam updateGoodsTeam = new GoodsTeam();
            updateGoodsTeam.setId(oldGoods.getId());
            updateGoodsTeam.setStock(oldGoods.getStock()-orderTeamGoods.getTotal());
            this.goodsTeamService.updateGoodsTeam(updateGoodsTeam);

            //补充订单产品信息
            orderTeamGoods.setPriceN(goodsProduct.getPriceVip());
            orderTeamGoods.setPriceO(goodsProduct.getPriceO());
            orderTeamGoods.setGoodsId(goodsProduct.getGoodsId());
        }

        //生成 上级订单ID
        String superOrderId = "";
        if(orderTeamOrderDto.getGoodsList().size()>1){
            superOrderId = this.idGererateFactory.nextId().toString();
        }

        String orderId = "";

        for(OrderTeamGoods orderTeamGoods:orderTeamOrderDto.getGoodsList()){
            OrderTeamOrder orderTeam = new OrderTeamOrder();
            orderTeam.setUserId(orderTeamOrderDto.getUserId());
            orderTeam.setPostFee(orderTeamGoods.getPostFee());
            orderTeam.setPricePay(orderTeamGoods.getPriceN().multiply(new BigDecimal(orderTeamGoods.getTotal())).add(orderTeam.getPostFee()));
            orderTeam.setPriceRealPay(orderTeam.getPricePay());
            orderTeam.setBuyerMsg(orderTeamOrderDto.getBuyerMsg());
            orderTeam.setConsigneeName(orderTeamOrderDto.getConsigneeName());
            orderTeam.setConsigneeTel(orderTeamOrderDto.getConsigneeTel());
            orderTeam.setAddress(orderTeamOrderDto.getAddress());
            orderTeam.setArea(orderTeamOrderDto.getArea());
            if(orderTeamOrderDto.getGoodsList().size()>1){
                orderTeam.setSuperOrderId(superOrderId);
            }

            orderTeam.setOrderNo(this.idGererateFactory.nextId().toString());
            orderTeam.setStatus(OrderStatus.TO_BE_PAID.getValue());
            orderTeam.setCreated(DateUtils.getNowDate());
            orderTeam.setDelFlag(0);
            orderTeam.setIsRefund(0);
            orderTeam.setId(idGererateFactory.nextStringId());
            this.orderTeamOrderService.insertOrderTeamOrder(orderTeam);
            //添加订单下的产品信息
            orderTeamGoods.setOrderId(orderTeam.getId());
            orderTeamGoods.setHasComent(0);
            orderTeamGoods.setId(idGererateFactory.nextStringId());
            this.orderTeamGoodsService.insertOrderTeamGoods(orderTeamGoods);

            if(orderTeamOrderDto.getGoodsList().size()>1){
                orderTeam.setSuperOrderId(superOrderId);
                orderId = superOrderId;
            }else{
                orderId = orderTeam.getId();
            }

            // 添加拼团订单人员表
            OrderTeamUser orderTeamUser = new OrderTeamUser();
            orderTeamUser.setId(idGererateFactory.nextStringId());
            orderTeamUser.setOrderId(orderTeam.getId());
            orderTeamUser.setCreateAt(DateUtils.getNowDate());
            orderTeamUser.setOrderTeamGoodsId(orderTeamGoods.getId());
            // 判断是否是订单发起人
//            if (orderSn != null) {
//                // 通过订单号查订单
//                OrderTeamOrderDto orderTeamByOrderNo = this.orderTeamOrderService.findByOrderNo(orderSn);
//                // 通过orderId查拼团订单人
//                OrderTeamUser orderTeamUserByOrderId = this.orderTeamUserService.findByOrderId(orderTeamByOrderNo.getId());
//                // 通过teamID查拼团订单条数
//                List<OrderTeamUser> listByTeamId = orderTeamUserService.findListByTeamId(orderTeamUserByOrderId.getTeamId());
//                // 判断是否超过拼团人数
//                GoodsTeam goodsTeamById = this.goodsTeamService.selectGoodsTeamById(orderTeamGoods.getGoodsId());
//                if (goodsTeamById.getNumber()>listByTeamId.size()) {
//                    orderTeamUser.setIsMain(0);
//                    orderTeamUser.setTeamId(orderTeamUserByOrderId.getTeamId());
//                }
//            }

            // 判断是否是拼团发起人
            if (!StringUtils.isBlank(orderTeamOrderDto.getMemberId())) {
                String oId = "";
                OrderTeamOrder oto = new OrderTeamOrder();
                oto.setStatus(9);
                oto.setUserId(orderTeamOrderDto.getMemberId());
                // 拼团订单列表
                List<OrderTeamOrder> teamOrderList = this.orderTeamOrderService.selectOrderTeamOrderList(oto);
                if (teamOrderList.size()>0) {
                    for (OrderTeamOrder orderTeamO:teamOrderList) {
                        // 某一条拼团订单
                        OrderTeamOrderDto byOrderNo = this.orderTeamOrderService.findByOrderNo(orderTeamO.getOrderNo());
                        for(OrderTeamGoods orderTGoods:orderTeamOrderDto.getGoodsList()){
                            OrderTeamGoodsDto teamGoodsDto = orderTeamGoodsService.findByOrderId(byOrderNo.getId());
                            if (teamGoodsDto.getGoodsId().equals(orderTGoods.getGoodsId())) {
                                oId = teamGoodsDto.getOrderId();
                            }
                        }
                    }
                    // 通过orderId查拼团订单人
                    OrderTeamUser orderTeamUserByOrderId = this.orderTeamUserService.findByOrderId(oId);
                    // 通过teamID查拼团订单条数
                    List<OrderTeamUser> listByTeamId = orderTeamUserService.findListByTeamId(orderTeamUserByOrderId.getTeamId());
                    // 判断是否超过拼团人数
                    GoodsTeam goodsTeamById = this.goodsTeamService.selectGoodsTeamById(orderTeamGoods.getGoodsId());
                    if (goodsTeamById.getNumber()>listByTeamId.size()) {
                        orderTeamUser.setIsMain(0);
                        orderTeamUser.setTeamId(orderTeamUserByOrderId.getTeamId());
                    } else {
                        orderTeamUser.setIsMain(1);
                        orderTeamUser.setTeamId(idGererateFactory.nextStringId());
                    }
                }else {
                    orderTeamUser.setIsMain(1);
                    orderTeamUser.setTeamId(idGererateFactory.nextStringId());
                    this.orderTeamUserService.insertOrderTeamUser(orderTeamUser);
                }
            } else {
                orderTeamUser.setIsMain(1);
                orderTeamUser.setTeamId(idGererateFactory.nextStringId());
                this.orderTeamUserService.insertOrderTeamUser(orderTeamUser);
            }
        }

        //删除购物车
        if(orderTeamOrderDto.getCartIds()!=null){
            this.shoppingCartService.deleteByIds(orderTeamOrderDto.getCartIds());
        }
        return RFactory.generateR(orderId);

    }

    /**
     * 发起支付 获取支付必要参数
     * @param uid
     * @param id
     * @param req
     * @return
     */
    @GetMapping("/wxpay")
    public R wxPay(@RequestParam String uid, @RequestParam String id, HttpServletRequest req){
        //查询订单是否存在
        OrderTeamOrder orderTeamOrder = this.orderTeamOrderService.selectOrderTeamOrderById(id);
        if(orderTeamOrder!=null){
            if(!orderTeamOrder.getUserId().equals(uid)){
                return R.error("订单不存在");
            }
            OrderTeamGoodsDto teamGoodsByOrderId = this.orderTeamGoodsService.findByOrderId(id);
            GoodsTeam goodsTeamById = this.goodsTeamService.selectGoodsTeamById(teamGoodsByOrderId.getGoodsId());
            if(goodsTeamById.getGroupEnd().getTime()< DateUtils.getNowDate().getTime()) {
                return R.error("拼团商品已下架");
            }
        }else{
            List<OrderTeamOrderDto> orderTeamOrders = this.orderTeamOrderService.findListBySuperOId(id);
            if(orderTeamOrders==null||orderTeamOrders.size()==0){
                return R.error("订单找不到");
            }
            BigDecimal price = new BigDecimal(0);
            for(OrderTeamOrder orderTeam :orderTeamOrders){
                price = price.add(orderTeam.getPriceRealPay());
            }
            orderTeamOrder = new OrderTeamOrder();
            orderTeamOrder.setOrderNo(id);
            orderTeamOrder.setPriceRealPay(price);
        }

        Member member = this.memberService.selectMemberById(uid);

        HashMap<String, Object> map = new HashMap<>();
        //时间戳
        map.put("timeStamp",(DateUtils.getNowDate().getTime()+"").substring(0,10));
        //package

        //调用统一下单接口拿到prepay_id
        SortedMap<String, Object> date = new TreeMap<String,Object>();

        //返回用前端的date2
        SortedMap<String, Object> date2 = new TreeMap<String,Object>();
        date2.put("appId",AppBeanInjector.weixinConfig.getAppId());
        date2.put("timeStamp",(DateUtils.getNowDate().getTime()+"").substring(0,10));
        date2.put("signType","MD5");

        date.put("appid",AppBeanInjector.weixinConfig.getAppId());
        date.put("attach","家禽生态订单");
        date.put("openid",member.getOpenid());
        date.put("body","家禽生态订单");
        date.put("mch_id",AppBeanInjector.weixinConfig.getMch_id());
        date.put("nonce_str",this.idGererateFactory.nextStringId());
        date.put("notify_url",AppBeanInjector.weixinConfig.getTeam_notify_url());//
        date.put("out_trade_no",orderTeamOrder.getOrderNo()+"-"+this.idGererateFactory.nextStringId());
        date.put("spbill_create_ip", StringUtils.getRemoteAddr(req));
        float sessionmoney = Float.parseFloat(orderTeamOrder.getPriceRealPay().toString());
        String finalmoney = String.format("%.2f", sessionmoney);
        finalmoney = finalmoney.replace(".", "");
        String newStr = finalmoney.replaceFirst("^0*", "");
        date.put("total_fee",newStr);
        date.put("trade_type","JSAPI");
        //统一下单 获取预支付ID
        String perpayId = WeixinUtils.getPerpayId(date,date2);

        date2.put("package",FBSStringUtil.format("prepay_id={0}",perpayId));

        map.put("package",FBSStringUtil.format("prepay_id={0}",perpayId));
        //paySign 签名
        map.put("paySign",WeixinUtils.createSign(WeixinUtils.CHARSET,date2));
        //随机字符串
        map.put("nonceStr",date2.get("nonceStr"));


        //生成支付记录
        PayLog payLog = new PayLog();
        payLog.setOutTradeNo((String) date.get("out_trade_no"));
        payLog.setStatus(0);
        payLog.setType(1);
        payLog.setCreated(DateUtils.getNowDate());
        payLog.setMemberId(uid);
        payLog.setResId(id);
        payLog.setPrice(orderTeamOrder.getPriceRealPay());
        this.payLogService.insertPayLog(payLog);


        return RFactory.generateR(map);
    }


    /**
     * 支付成功的回调参数
     * @param req
     * @param res
     * @return
     */
    @PostMapping("/result")
    public Object weixinResult(HttpServletRequest req, HttpServletResponse res){
        try {
            InputStream inStream = req.getInputStream();
            ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inStream.read(buffer)) != -1) {
                outSteam.write(buffer, 0, len);
            }

            System.out.println("~~~~~~~~~~~~~~~~付款成功~~~~~~~~~");
            outSteam.close();
            inStream.close();
            String result = new String(outSteam.toByteArray(), "utf-8");// 获取微信调用我们notify_url的返回信息
            Map<Object, Object> mapFromXml = WeixinUtils.doXMLParse(result);
            SortedMap<String ,String > sortedMap = new TreeMap();
            if (mapFromXml.get("result_code").toString().equalsIgnoreCase("SUCCESS")) {

                PayLog payLog = this.payLogService.selectPayLogByNo(mapFromXml.get("out_trade_no").toString());
                if(payLog.getStatus()==0){

                    String orderNo = mapFromXml.get("out_trade_no").toString().split("-")[0];
                    Date date = new Date();
                    OrderTeamOrderDto orderTeamOrder = this.orderTeamOrderService.findByOrderNo(orderNo);
                    if (orderTeamOrder!=null){
                        if (orderTeamOrder.getStatus()>0){
                            return "fail";
                        }

                        //  验签成功后
                        orderTeamOrder.setStatus(9);
                        orderTeamOrder.setPayType(OrderPayType.WEIXIN.getValue());
                        orderTeamOrder.setUpdateTime(date);
                        orderTeamOrder.setOutTradeNo(mapFromXml.get("out_trade_no").toString());
                        orderTeamOrderService.updateOrderTeamOrder(orderTeamOrder);

                        //产品销量新增

                        //查询订单下的规格
                        List<OrderTeamGoodsDto> listByOrderId = this.orderTeamGoodsService.findListByOrderId(orderTeamOrder.getId());
                        for(OrderTeamGoodsDto orderTeamGoodsDto:listByOrderId){
                            GoodsTeam goodsTeam = this.goodsTeamService.selectGoodsTeamById(orderTeamGoodsDto.getGoodsId());
                            GoodsTeam update = new GoodsTeam();
                            update.setId(goodsTeam.getId());
                            update.setMonthlySales(goodsTeam.getMonthlySales()+orderTeamGoodsDto.getTotal());
                            this.goodsTeamService.updateGoodsTeam(update);
                        }
                        //更新支付记录
                        PayLog updatePayLog = new PayLog();
                        updatePayLog.setId(payLog.getId());
                        updatePayLog.setStatus(1);
                        this.payLogService.updatePayLog(updatePayLog);

                        // 通过orderId查拼团订单人
                        OrderTeamUser orderTeamUserByOrderId = this.orderTeamUserService.findByOrderId(orderTeamOrder.getId());
                        // 通过teamID查拼团订单条数
                        List<OrderTeamUser> listByTeamId = this.orderTeamUserService.findListByTeamId(orderTeamUserByOrderId.getTeamId());
                        // 查订单拼团商品
                        OrderTeamGoods orderTeamGoods = this.orderTeamGoodsService.findByOrderId(orderTeamOrder.getId());
                        // 查拼团商品
                        GoodsTeam goodsTeamById = this.goodsTeamService.selectGoodsTeamById(orderTeamGoods.getGoodsId());
                        // 判断是否超过拼团人数
                        if (goodsTeamById.getNumber()==listByTeamId.size()) {
                            orderTeamOrder.setStatus(1);
                            // 拼团人数够了团队人员订单变为待发货
                            for (OrderTeamUser OrderTUser:listByTeamId) {
                                OrderTeamOrder teamOrderById = this.orderTeamOrderService.selectOrderTeamOrderById(OrderTUser.getOrderId());
                                if (teamOrderById.getStatus() == 9) {
                                    OrderTeamOrder updateTeamOrder = new OrderTeamOrder();
                                    updateTeamOrder.setId(teamOrderById.getId());
                                    updateTeamOrder.setStatus(1);
                                    this.orderTeamOrderService.updateOrderTeamOrder(updateTeamOrder);
                                }

                            }
                        }

                    }else{
                        List<OrderTeamOrderDto> listBySuperOId = this.orderTeamOrderService.findListBySuperOId(orderNo);
                        if(listBySuperOId==null||listBySuperOId.size()==0){
                            sortedMap.put("return_code","FAIL");
                            sortedMap.put("return_msg","签名失败");
                            res.reset();
                            res.getWriter().write(parseXML(sortedMap));
                        }else{
                            for(OrderTeamOrderDto orderTeamOrderDto: listBySuperOId){
                                orderTeamOrderDto.setStatus(9);
                                orderTeamOrderDto.setPayType(OrderPayType.WEIXIN.getValue());
                                orderTeamOrderDto.setUpdateTime(date);
                                orderTeamOrderDto.setOutTradeNo(mapFromXml.get("out_trade_no").toString());
                                orderTeamOrderService.updateOrderTeamOrder(orderTeamOrderDto);

                                //产品销量新增

                                //查询订单下的规格
                                List<OrderTeamGoodsDto> listByOrderId = this.orderTeamGoodsService.findListByOrderId(orderTeamOrderDto.getId());
                                for(OrderTeamGoodsDto orderTeamGoodsDto:listByOrderId){
                                    GoodsTeam goodsTeam = this.goodsTeamService.selectGoodsTeamById(orderTeamGoodsDto.getGoodsId());
                                    GoodsTeam update = new GoodsTeam();
                                    update.setId(goodsTeam.getId());
                                    update.setMonthlySales(goodsTeam.getMonthlySales()+orderTeamGoodsDto.getTotal());
                                    this.goodsTeamService.updateGoodsTeam(update);
                                }
                            }
                            //更新支付记录
                            PayLog updatePayLog = new PayLog();
                            updatePayLog.setId(payLog.getId());
                            updatePayLog.setStatus(1);
                            this.payLogService.updatePayLog(updatePayLog);
                        }
                    }

                }


                sortedMap.put("return_code","SUCCESS");
                sortedMap.put("return_msg","OK");

                BufferedOutputStream out = new BufferedOutputStream(
                        res.getOutputStream());
                out.write(parseXML(sortedMap).getBytes());
                out.flush();
                out.close();
            }else {
                sortedMap.put("return_code","FAIL");
                sortedMap.put("return_msg","签名失败");
                BufferedOutputStream out = new BufferedOutputStream(
                        res.getOutputStream());
                out.write(parseXML(sortedMap).getBytes());
                out.flush();
                out.close();
            }
            return "success";
        } catch (Exception e) {
            return "failure";
        }
    }


    //输出XML
    public String parseXML(Map map) {
        StringBuffer sb = new StringBuffer();
        sb.append("<xml>\n");
        Set es = map.entrySet();
        Iterator it = es.iterator();
        while(it.hasNext()) {
            Map.Entry entry = (Map.Entry)it.next();
            String k = (String)entry.getKey();
            String v = (String)entry.getValue();
            if(null != v && !"".equals(v) && !"appkey".equals(k)) {

                sb.append("<" + k +"><![CDATA[" + v + "]]></" + k + ">\n");
            }
        }
        sb.append("</xml>");
        return sb.toString();
    }


    /**
     * 订单收货
     * @param map
     * @return
     */
    @PostMapping("/receipt")
    public R orderReceipt(@RequestBody Map map){
        String uid = (String) map.get("uid");
        String id = (String) map.get("id");

        //判断订单信息是否存在
        OrderTeamOrder orderTeamOrder = this.orderTeamOrderService.selectOrderTeamOrderById(id);
        //订单不存在 或者 订单并非当前用户 或者 订单 状态不是待收货
        if(orderTeamOrder==null||!orderTeamOrder.getUserId().equals(uid)||!orderTeamOrder.getStatus().equals(OrderStatus.TO_BE_RECEIVED.getValue())){
            return R.error("订单未找到");
        }

        OrderTeamOrder update = new OrderTeamOrder();
        update.setStatus(4);
        update.setId(id);
        update.setCloseTime(DateUtils.getNowDate());
        this.orderTeamOrderService.updateOrderTeamOrder(update);

        return R.ok();
    }

    /**
     * 查询订单列表
     * @param status
     * @param uid
     * @return
     */
    @GetMapping
    public R orderList(@RequestParam(required = false) Integer[] status,@RequestParam String uid,@RequestParam(required = false) Integer refund){
        startPage();
        List<OrderTeamOrderDto> orderTeamOrderDtos = this.orderTeamOrderService.findListByStatusAndUid(status,uid,refund);
        if(orderTeamOrderDtos!=null){
            for(OrderTeamOrderDto orderTeamDto:orderTeamOrderDtos){
                orderTeamDto.setGoodsList(this.orderTeamGoodsService.findListByOrderId(orderTeamDto.getId()));
            }
        }
        return RFactory.generateR(orderTeamOrderDtos);
    }

    /**
     * 查询订单列表
     * @param uid
     * @return
     */
    @GetMapping("/orderList")
    public R orderList1(@RequestParam String uid){
        startPage();
        List<OrderTeamOrderDto> orderTeamOrders = this.orderTeamOrderService.selectOTOList(uid);
        if(orderTeamOrders!=null){
            for(OrderTeamOrderDto orderTeamDto:orderTeamOrders){
                orderTeamDto.setGoodsList(this.orderTeamGoodsService.findListByOrderId(orderTeamDto.getId()));
            }
        }
        return RFactory.generateR(getDataTable(orderTeamOrders));
    }


    /**
     * 查询订单详情
     * @param id
     * @return
     */
    @GetMapping("/info")
    public R orderInfo(@RequestParam String id){
        OrderTeamOrderDto orderTeamDto = this.orderTeamOrderService.findByOrderId(id);
        if(orderTeamDto!=null){
            orderTeamDto.setGoodsList(this.orderTeamGoodsService.findListByOrderId(id));
            return RFactory.generateR(orderTeamDto);
        }else{
            List<OrderTeamOrderDto> listBySuperOId = this.orderTeamOrderService.findListBySuperOId(id);
            if(listBySuperOId==null||listBySuperOId.size()==0){
                return R.error("订单不存在");
            }
            OrderTeamOrderDto orderTeam = listBySuperOId.get(0);
            ArrayList<OrderTeamGoodsDto> orderTeamGoods = new ArrayList<>();

            BigDecimal price = new BigDecimal(0);
            for(OrderTeamOrderDto orderTeamOrderDto:listBySuperOId){
                OrderTeamGoodsDto orderTeamGoodsDto = this.orderTeamGoodsService.findListByOrderId(orderTeamOrderDto.getId()).get(0);
                price = price.add(orderTeamGoodsDto.getPriceN().multiply(new BigDecimal(orderTeamGoodsDto.getTotal())).add(orderTeamOrderDto.getPostFee())).setScale(2,BigDecimal.ROUND_HALF_UP);
                orderTeamGoods.add(orderTeamGoodsDto);
            }
            orderTeam.setGoodsList(orderTeamGoods);
            orderTeam.setPriceRealPay(price.setScale(2,BigDecimal.ROUND_HALF_UP));
            orderTeam.setOrderNo(id);
            return RFactory.generateR(orderTeam);

        }

    }

    /**
     * 取消订单
     * @param map
     * @return
     */
    @PostMapping("/remove")
    public R removeOrder(@RequestBody Map map){
        String uid= (String) map.get("uid");
        String id = (String) map.get("id");
        //查询订单是否存在
        OrderTeamOrder orderTeamOrder = this.orderTeamOrderService.selectOrderTeamOrderById(id);
        if(orderTeamOrder==null||!orderTeamOrder.getUserId().equals(uid)){
            return R.error("订单不存在");
        }
        if(!orderTeamOrder.getStatus().equals(OrderStatus.TO_BE_PAID.getValue())){
            return R.error("该状态下,不可取消");
        }
        OrderTeamOrder orderTeam = new OrderTeamOrder();
        orderTeam.setId(id);
        orderTeam.setStatus(OrderStatus.CANCEL.getValue());
        this.orderTeamOrderService.updateOrderTeamOrder(orderTeam);
        //释放订单下的产品库存
        List<OrderTeamGoodsDto> listByOrderId = this.orderTeamGoodsService.findListByOrderId(id);
        for(OrderTeamGoodsDto orderTeamGoodsDto:listByOrderId){
            GoodsProduct product = this.goodsProductService.selectGoodsProductById(orderTeamGoodsDto.getProductId());
            //判断规格是否存在 以及 规格是否已删除
            if(product==null||product.getStatus().equals(1)){
                continue;
            }
            //修改规格库存
            GoodsProduct goodsProduct = new GoodsProduct();
            goodsProduct.setStock(product.getStock()+orderTeamGoodsDto.getTotal().intValue());
            goodsProduct.setId(orderTeamGoodsDto.getProductId());
            this.goodsProductService.updateGoodsProduct(goodsProduct);

            //修改产品库存
            GoodsTeam goodsT = this.goodsTeamService.selectGoodsTeamById(orderTeamGoodsDto.getGoodsId());

            GoodsTeam goodsTeam = new GoodsTeam();
            goodsTeam.setId(orderTeamGoodsDto.getGoodsId());
            goodsTeam.setStock(goodsT.getStock()+orderTeamGoodsDto.getTotal());
            this.goodsTeamService.updateGoodsTeam(goodsTeam);
        }


        return R.ok();
    }

    /**
     * 新增评价
     * @param orderCommentDto
     * @return
     */
    @PostMapping("/comment")
    @Transactional
    public R addOrderGoodsComment(@RequestBody OrderCommentDto orderCommentDto){
        //判断订单产品是否已评论
        OrderTeamGoods orderTeamGoods = new OrderTeamGoods();
        orderTeamGoods.setProductId(orderCommentDto.getProductId());
        orderTeamGoods.setOrderId(orderCommentDto.getOrderId());
        List<OrderTeamGoods> oldOrderTeamGoods = this.orderTeamGoodsService.selectOrderTeamGoodsList(orderTeamGoods);
        if(oldOrderTeamGoods==null||oldOrderTeamGoods.size()==0||oldOrderTeamGoods.get(0).getHasComent().equals(1)){
            return R.error("不可以进行评论");
        }
        orderCommentDto.setCreated(DateUtils.getNowDate());
        orderCommentDto.setStatus(0);
        this.orderCommentService.insertOrderComment(orderCommentDto);

        //上传评论的图片
        if(orderCommentDto.getMultipartFiles()!=null&&orderCommentDto.getMultipartFiles().size()!=0){
            for(CommentImg commentImg:orderCommentDto.getMultipartFiles()){
                commentImg.setCommentId(orderCommentDto.getId());
                this.commentImgService.insertCommentImg(commentImg);
            }
        }


        //更新订单下的产品状态
        OrderTeamGoods update = new OrderTeamGoods();
        update.setId(oldOrderTeamGoods.get(0).getId());
        update.setHasComent(1);
        this.orderTeamGoodsService.updateOrderTeamGoods(update);
        //判断订单下的产品是否已经全部评论
        OrderTeamGoods oo = new OrderTeamGoods();
        oo.setHasComent(0);
        oo.setOrderId(orderCommentDto.getOrderId());
        List<OrderTeamGoods> og = this.orderTeamGoodsService.selectOrderTeamGoodsList(oo);
        if(og==null||og.size()==0){
            OrderTeamOrder orderTeamOrder = new OrderTeamOrder();
            orderTeamOrder.setId(orderCommentDto.getOrderId());
            orderTeamOrder.setStatus(OrderStatus.COMPLETE.getValue());
            this.orderTeamOrderService.updateOrderTeamOrder(orderTeamOrder);
        }

        return R.ok();
    }

    /**
     * 新增售后
     * @param orderRefuse
     * @return
     */
    @PostMapping("/refund")
    @Transactional
    public R orderRefund(@RequestBody OrderRefuse orderRefuse){
        OrderTeamOrder oldOrder = this.orderTeamOrderService.selectOrderTeamOrderById(orderRefuse.getOrderId());
        if(oldOrder==null){
            return R.error("订单不存在");
        }
        //查询订单下是否已有售后单 防止重复提交
        OrderRefuse byNo = this.orderRefuseService.findByOrderId(oldOrder.getId());
        if(byNo!=null){
            return R.error("请勿重复提交");
        }

        orderRefuse.setPrice(oldOrder.getPriceRealPay());
        orderRefuse.setCreated(DateUtils.getNowDate());
//		orderRefuse.setRefundNo(this.idGererateFactory.nextStringId());
        orderRefuse.setStatus(0);
        this.orderRefuseService.insertOrderRefuse(orderRefuse);
        //修改订单为售后单
        OrderTeamOrder orderTeamOrder = new OrderTeamOrder();
        orderTeamOrder.setId(orderRefuse.getOrderId());
        orderTeamOrder.setIsRefund(1);
        this.orderTeamOrderService.updateOrderTeamOrder(orderTeamOrder);
        return R.ok();
    }

    /**
     * 查询快递信息
     */
    @GetMapping("/express")
    public R orderExpress(@RequestParam String uid,@RequestParam String id){
        //查询订单是否存在
        OrderTeamOrderDto byOrderId = this.orderTeamOrderService.findByOrderId(id);
        if(byOrderId==null||!byOrderId.getUserId().equals(uid)){
            return R.error("订单不存在");
        }
        byOrderId.setGoodsList(this.orderTeamGoodsService.findListByOrderId(id));
        try {
//			JSONObject yd = AppBeanInjector.expressUtil.getOrderTracesByJson(byOrderId.getShippingCompanyCode(), byOrderId.getShippingCode());
            JSONObject expressJsonData = AppBeanInjector.kd100Util.getExpressJsonData(byOrderId.getShippingCompanyCode(), byOrderId.getShippingCode());
            HashMap<String, Object> map = new HashMap<>();
            map.put("order",byOrderId);
            map.put("express",expressJsonData.toString());
            return RFactory.generateR(map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.error();
    }


}
